Skip to content

ProgramAsJudge reward

Bases: Reward

Use a Program as judge; for grading flows the built-in judges cannot express.

You can use this to create advanced reward functions that use a Synalinks Program. The program returns a data model with a reward field, and gets what it declares:

  • a functional program with one input gets the prediction y_pred (no ground truth needed), with two inputs [y_true, y_pred], with three [y_true, y_pred, x], x being the inputs of the program judged (e.g. to grade an answer against its question);
  • a subclassed program gets [y_true, y_pred], and x as a keyword when its call declares an x argument: call(self, inputs, x=None). If its call declares y_true, it gets the prediction alone as its first argument and the ground truth as a keyword (None without labels): call(self, y_pred, y_true=None, x=None).

x is None when the reward is called without it, so declare that input optional=True (and y_true too, to judge without a ground truth).

Masks name the fields as the judge sees them, prefixed by where they come from: input_ for the program's inputs, output_ for its prediction and gold_ for the ground truth. out_mask=["input_context"] keeps a large retrieved context away from the judge; in_mask=["input_query", "output_answer"] shows it only the question and the answer.

Example:

import synalinks

class Query(synalinks.DataModel):
    query: str = synalinks.Field(description="The user query")

class Answer(synalinks.DataModel):
    answer: str = synalinks.Field(description="The answer")

async def build_judge(language_model):
    y_true = synalinks.Input(data_model=Answer, optional=True)
    y_pred = synalinks.Input(data_model=Answer)
    x = synalinks.Input(data_model=Query, optional=True)
    # `|` skips the inputs that are `None`.
    graded = x | (y_pred | y_true)
    critique = await synalinks.SelfCritique(
        language_model=language_model,
    )(graded)
    return synalinks.Program(inputs=[y_true, y_pred, x], outputs=critique)

async def main():
    language_model = synalinks.LanguageModel(model="ollama/mistral")
    # ... your program declaration
    program.compile(
        reward=synalinks.rewards.ProgramAsJudge(
            program=await build_judge(language_model),
        ),
        optimizer=synalinks.optimizers.RandomFewShot(),
    )

Parameters:

Name Type Description Default
program Program

The reward program to wrap.

required
reduction str

Optional. How the per-sample rewards of a batch are reduced, one of "mean", "sum", "min", "max", "none" or None (see Reward). Defaults to "mean".

'mean'
name str

Optional. string name of the reward instance.

None
in_mask list

Optional. list of keys to keep to compute the reward.

None
out_mask list

Optional. list of keys to remove to compute the reward.

None
in_mask_pattern str

Optional. Regex pattern; fields whose names match are kept (combined with in_mask via OR).

None
out_mask_pattern str

Optional. Regex pattern; fields whose names match are dropped (combined with out_mask via OR).

None
Source code in synalinks/src/rewards/reward_wrappers.py
@synalinks_export(
    [
        "synalinks.ProgramAsJudge",
        "synalinks.rewards.ProgramAsJudge",
    ]
)
class ProgramAsJudge(Reward):
    """Use a Program as judge; for grading flows the built-in judges cannot express.

    You can use this to create advanced reward functions that use a Synalinks
    `Program`. The program returns a data model with a `reward` field, and
    gets what it declares:

    - a functional program with one input gets the prediction `y_pred` (no
      ground truth needed), with two inputs `[y_true, y_pred]`, with three
      `[y_true, y_pred, x]`, `x` being the inputs of the program judged (e.g.
      to grade an answer against its question);
    - a subclassed program gets `[y_true, y_pred]`, and `x` as a keyword when
      its `call` declares an `x` argument: `call(self, inputs, x=None)`. If
      its `call` declares `y_true`, it gets the prediction alone as its first
      argument and the ground truth as a keyword (`None` without labels):
      `call(self, y_pred, y_true=None, x=None)`.

    `x` is `None` when the reward is called without it, so declare that input
    `optional=True` (and `y_true` too, to judge without a ground truth).

    Masks name the fields as the judge sees them, prefixed by where they come
    from: `input_` for the program's inputs, `output_` for its prediction and
    `gold_` for the ground truth. `out_mask=["input_context"]` keeps a large
    retrieved context away from the judge; `in_mask=["input_query",
    "output_answer"]` shows it only the question and the answer.

    Example:

    ```python
    import synalinks

    class Query(synalinks.DataModel):
        query: str = synalinks.Field(description="The user query")

    class Answer(synalinks.DataModel):
        answer: str = synalinks.Field(description="The answer")

    async def build_judge(language_model):
        y_true = synalinks.Input(data_model=Answer, optional=True)
        y_pred = synalinks.Input(data_model=Answer)
        x = synalinks.Input(data_model=Query, optional=True)
        # `|` skips the inputs that are `None`.
        graded = x | (y_pred | y_true)
        critique = await synalinks.SelfCritique(
            language_model=language_model,
        )(graded)
        return synalinks.Program(inputs=[y_true, y_pred, x], outputs=critique)

    async def main():
        language_model = synalinks.LanguageModel(model="ollama/mistral")
        # ... your program declaration
        program.compile(
            reward=synalinks.rewards.ProgramAsJudge(
                program=await build_judge(language_model),
            ),
            optimizer=synalinks.optimizers.RandomFewShot(),
        )
    ```

    Args:
        program (Program): The reward program to wrap.
        reduction (str): Optional. How the per-sample rewards of a batch are
            reduced, one of `"mean"`, `"sum"`, `"min"`, `"max"`, `"none"` or
            `None` (see `Reward`). Defaults to `"mean"`.
        name (str): Optional. string name of the reward instance.
        in_mask (list): Optional. list of keys to keep to compute the reward.
        out_mask (list): Optional. list of keys to remove to compute the reward.
        in_mask_pattern (str): Optional. Regex pattern; fields whose names match
            are kept (combined with ``in_mask`` via OR).
        out_mask_pattern (str): Optional. Regex pattern; fields whose names match
            are dropped (combined with ``out_mask`` via OR).
    """

    # Set by a judge that builds its own program from its arguments.
    program_class = None

    def __init__(
        self,
        program,
        reduction="mean",
        name=None,
        description=None,
        in_mask=None,
        out_mask=None,
        in_mask_pattern=None,
        out_mask_pattern=None,
    ):
        super().__init__(
            name=name,
            reduction=reduction,
            in_mask=in_mask,
            out_mask=out_mask,
            in_mask_pattern=in_mask_pattern,
            out_mask_pattern=out_mask_pattern,
            description=description,
        )
        self.program = program
        if description is None and type(self) is ProgramAsJudge:
            self.description = program.description
        for name in (in_mask or []) + (out_mask or []):
            if not name.startswith(("input_", "output_", "gold_")):
                warnings.warn(
                    f"{self.__class__.__name__}: mask field {name!r} matches "
                    "nothing: a judge's masks name prefixed fields, e.g. "
                    f"'output_{name}' or 'input_{name}'.",
                    stacklevel=2,
                )

    def mask(self, y_true, y_pred, x=None):
        """Keep the top-level fields whose prefixed name (`gold_`, `output_`,
        `input_`) passes the masks, on each side."""
        masks = {
            "in_mask": self.in_mask,
            "in_mask_pattern": self.in_mask_pattern,
            "out_mask": self.out_mask,
            "out_mask_pattern": self.out_mask_pattern,
        }
        if not any(masks.values()):
            return super().mask(y_true, y_pred, x)

        def side(model, prefix):
            if model is None:
                return None
            names = {f"{prefix}_{key}": key for key in model.get_json()}
            kept = dict.fromkeys(names)
            if self.in_mask or self.in_mask_pattern:
                kept = in_mask_json(
                    kept, self.in_mask, self.in_mask_pattern, recursive=False
                )
            if self.out_mask or self.out_mask_pattern:
                kept = out_mask_json(
                    kept, self.out_mask, self.out_mask_pattern, recursive=False
                )
            return model.in_mask(mask=[names[key] for key in kept], recursive=False)

        y_true, y_pred, x = (mask_data_models(v) for v in (y_true, y_pred, x))
        return (
            tree.map_structure(lambda m: side(m, "gold"), y_true),
            tree.map_structure(lambda m: side(m, "output"), y_pred),
            tree.map_structure(lambda m: side(m, "input"), x),
        )

    async def close(self):
        """Close the judge's program: an agent judge's sandbox, say. Idempotent."""
        await self.program.close()

    async def call(self, y_true, y_pred, x=None):
        if not y_pred:
            # The judged program produced nothing: no judge call, the lowest grade.
            return 0.0
        # A functional program gets what it declares, in order (`y_pred` alone,
        # `y_true` first, `x` last); a subclassed one gets the keywords its
        # `call` names (`**kwargs` may forward them on, so it does not count).
        nb_inputs = len(getattr(self.program, "inputs", None) or ())
        call = self.program.call
        kwargs = {}
        if accepts_argument(call, "x", var_keyword=False):
            kwargs["x"] = x
        if nb_inputs == 1:
            result = await self.program(y_pred)
        elif nb_inputs == 3:
            result = await self.program([y_true, y_pred, x])
        elif accepts_argument(call, "y_true", var_keyword=False):
            result = await self.program(y_pred, y_true=y_true, **kwargs)
        else:
            result = await self.program([y_true, y_pred], **kwargs)
        if result is None or result.get("reward") is None:
            warnings.warn(
                f"{self.__class__.__name__}: judge program returned None or no "
                "reward (likely an LLM / provider failure). Scoring this sample as "
                "0.0 and continuing. Check the underlying language model "
                "and structured-output configuration.",
                RuntimeWarning,
                stacklevel=2,
            )
            return 0.0
        return float(result.get("reward"))

    def get_config(self):
        config = super().get_config()
        config["program"] = serialization_lib.serialize_synalinks_object(self.program)
        return config

    @classmethod
    def from_config(cls, config):
        if cls.program_class is None:
            if "program" in config:
                config = serialization_lib.deserialize_synalinks_object(config)
            return cls(**config)
        # A judge that builds its own program takes the program's arguments, not
        # the program: building it would also build what it opens (a sandbox).
        config = dict(config)
        program = config.pop("program")
        arguments = cls.program_class.resolve_config(program["config"])
        for key in ("name", "description", "trainable"):
            arguments.pop(key, None)
        return cls(**arguments, **config)

    def __repr__(self):
        return f"<ProgramAsJudge({self.program})>"

close() async

Close the judge's program: an agent judge's sandbox, say. Idempotent.

Source code in synalinks/src/rewards/reward_wrappers.py
async def close(self):
    """Close the judge's program: an agent judge's sandbox, say. Idempotent."""
    await self.program.close()

mask(y_true, y_pred, x=None)

Keep the top-level fields whose prefixed name (gold_, output_, input_) passes the masks, on each side.

Source code in synalinks/src/rewards/reward_wrappers.py
def mask(self, y_true, y_pred, x=None):
    """Keep the top-level fields whose prefixed name (`gold_`, `output_`,
    `input_`) passes the masks, on each side."""
    masks = {
        "in_mask": self.in_mask,
        "in_mask_pattern": self.in_mask_pattern,
        "out_mask": self.out_mask,
        "out_mask_pattern": self.out_mask_pattern,
    }
    if not any(masks.values()):
        return super().mask(y_true, y_pred, x)

    def side(model, prefix):
        if model is None:
            return None
        names = {f"{prefix}_{key}": key for key in model.get_json()}
        kept = dict.fromkeys(names)
        if self.in_mask or self.in_mask_pattern:
            kept = in_mask_json(
                kept, self.in_mask, self.in_mask_pattern, recursive=False
            )
        if self.out_mask or self.out_mask_pattern:
            kept = out_mask_json(
                kept, self.out_mask, self.out_mask_pattern, recursive=False
            )
        return model.in_mask(mask=[names[key] for key in kept], recursive=False)

    y_true, y_pred, x = (mask_data_models(v) for v in (y_true, y_pred, x))
    return (
        tree.map_structure(lambda m: side(m, "gold"), y_true),
        tree.map_structure(lambda m: side(m, "output"), y_pred),
        tree.map_structure(lambda m: side(m, "input"), x),
    )